package ocr.view;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;

import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;

import ocr.server.ServerV;

public class Main extends Frame implements ActionListener {

	JButton start;
	JList clients;
	JLabel serverStatus;

	ServerV server;
	
	ArrayList<String> connections;

	public Main() {
		// TODO Auto-generated constructor stub
		this.setLayout(new BorderLayout());
		this.setTitle("OCR Server");
		this.setSize(600, 500);

		// start west panel
		JPanel westp = new JPanel();
		westp.setLayout(new BorderLayout());

		start = new JButton("Start");
		start.addActionListener(this);

		serverStatus = new JLabel("click start button to start server");
		westp.add(serverStatus, BorderLayout.CENTER);

		westp.add(start, BorderLayout.NORTH);

		this.add(westp, BorderLayout.WEST);

		// end add west panel

		connections = new ArrayList<String>();
		// list data
		clients = new JList();
		clients.setModel(new DefaultListModel());
		clients.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

		JScrollPane listPane = new JScrollPane(clients);
		listPane.setPreferredSize(new Dimension(400, 400));

		
		this.add(listPane, BorderLayout.CENTER);
		this.setVisible(true);

	}

	@Override
	public void actionPerformed(ActionEvent e) {
		// TODO Auto-generated method stub
		if (e.getSource() == start) {
			String text = start.getText();
			if (text.equals("Start")) {
				server = new ServerV(this, 6666);
				start.setText("Stop");
			} else {
				server.stopServer();
				start.setText("Start");
			}
		}
	}

	public void serverStatusChange(String status){
		serverStatus.setText(status);
	}
	
	public void acceptConnection(String clientinfo){
		clients.removeAll();
		connections.add(clientinfo);
		DefaultListModel model = (DefaultListModel)clients.getModel();
		model.addElement(clientinfo);
	}
	public static void main(String[] args) {
		new Main();
	}
}
